# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  before_filter :authorize, :except => :login
  before_filter :set_locale
  
  layout "public"
  
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
  
  protected
    def authorize
      @user = User.find_by_id session[:user_id]
      unless @user && authorize_with_right(@user)
        session[:original_uri] = request.request_uri
        flash[:notice] = "Veuillez vous authentifier, droit insuffisant"
        redirect_to :controller => :sessions, :action => :login
      end
    end

    def set_locale
      session[:locale] = params[:locale] if params[:locale]
      I18n.locale = session[:locale] || I18n.default_locale
    
      locale_path = "#{LOCALES_DIRECTORY}#{I18n.locale}.yml"
    
      unless I18n.load_path.include? locale_path
        I18n.load_path << locale_path
        I18n.backend.send(:init_translations)
      end
    
    rescue Exception => err
      logger.error err
      flash.now[:notice] = "#{I18n.locale} translation not Available"
    
      I18n.load_path -= [locale_path]
      I18n.locale = session[:locale] = I18n.default_locale
    end


    def authorize_with_right(user)
      Rule.can_view_site?(user)
    end
end
